<!DOCTYPE HTML>
<html lang="zh">

    <head>
        <title>websocket测试</title>
        <meta charset="utf-8">
        <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
    </head>

    <body>
        <div>
            <button id="connect" type="button" onclick="connect()">连接</button>
            <button id="disconnect" type="button" disabled="disabled" onclick="disconnect()">断开连接</button>
            <br/>
            <label for="name">用户名：</label>
            <input id="name" type="text" placeholder="用户名">
            <br/>
        </div>
        <div id="chat">
            <label for="text">消息:</label><input id="text" type="text"/>
            <button onclick="sendMessage()">发送</button>
            <div id="message"></div>
        </div>
    </body>
    <script type="text/javascript">
        let socket = null;
        //判断当前浏览器是否支持WebSocket
        if ('WebSocket' in window) {
            socket = new WebSocket("ws://localhost:8090/websocket");
            setButton(true)
        } else {
            alert('Not support websocket')
        }
        socket.onerror = err => {
            console.log(err);
            setMessageInnerHTML("发生异常");
        }
        socket.onopen = event => {
            console.log(event);
            setMessageInnerHTML("连接成功");
        }
        socket.onmessage = event => {
            console.log(event);
            setMessageInnerHTML(event.data);
        }
        socket.onclose = () => {
            console.log("连接关闭");
            setMessageInnerHTML("连接关闭");
        };

        function setButton(flag) {
            $("#connect").prop("disabled", flag)
            $("#disconnect").prop("disabled", !flag)
            if (flag) {
                $("#chat").show()
            } else {
                $("#chat").hide()
            }
        }

        function connect() {
            if (!$("#name").val()) {
                return;
            }
            socket = new WebSocket("ws://localhost:8090/websocket");
            setButton(true)
        }

        function disconnect() {
            socket.close();
            setButton(false)
        }

        /**
         * 监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，
         * 防止连接还没断开就关闭窗口，server端会抛异常。
         */
        window.onbeforeunload = function () {
            disconnect();
        }

        function setMessageInnerHTML(innerHTML) {
            document.getElementById('message').innerHTML += innerHTML + '<br/>';
        }

        function sendMessage() {
            if (socket.readyState === 1) {
                const message = JSON.stringify({
                    'name': $("#name").val(),
                    'content': $("#text").val()
                })
                socket.send(message)
            } else {
                alert("尚未建立websocket连接");
            }
        }
    </script>
</html>